﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.Caching;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;

namespace Mystery.SharePoint.WebControls
{
    /// <summary>
    /// Displays a warning indicator when the quota is being reached. 
    /// </summary>
    class QuotaWarningIndicator : WebControl
    {
        long _storageWarningLevel = -1;
        long _storageMaximumLevel = -1;
        long _storage = -1;
        string _warningKey = string.Empty;
        string _maximumKey = string.Empty;
        string _storageKey = string.Empty;

        private long StorageWarningLevel 
        {
            get
            {
                _storageWarningLevel = this.Page.Cache.Read<long>(_warningKey, -1);
                if (_storageWarningLevel < 0)
                {
                    RefreshValues();
                }
                return _storageWarningLevel;
            }
        }
        private long StorageMaximumLevel
        {
            get
            {
                _storageMaximumLevel = this.Page.Cache.Read<long>(_maximumKey, -1);
                if (_storageMaximumLevel < 0)
                {
                    RefreshValues();
                }
                return _storageMaximumLevel;
            }
        }
        private long Storage
        {
            get
            {
                _storage = this.Page.Cache.Read<long>(_storageKey, -1);
                if (_storage < 0)
                {
                    RefreshValues();
                }
                return _storage;
            }
        }

        public QuotaWarningIndicator()
        {
            // cannot do this in the variable declaration since the method uses SPContext
            // if the control gets added by a feature activated outside web context, it will fail
            _storageKey = GetCacheKey("Storage");
            _warningKey = GetCacheKey("Warning");
            _maximumKey = GetCacheKey("Maximum");
        }
        private void RefreshValues()
        {
            // refresh all values even if only one is missing from the cache
            SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        _storageWarningLevel = site.Quota.StorageWarningLevel;
                        _storageMaximumLevel = site.Quota.StorageMaximumLevel;
                        _storage = site.Usage.Storage;
                    }
                });

            DateTime expires = DateTime.Now.AddMinutes(10);

            this.Page.Cache.Add(_storageKey, _storage, null, expires, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            this.Page.Cache.Add(_warningKey, _storageWarningLevel, null, expires, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            this.Page.Cache.Add(_maximumKey, _storageMaximumLevel, null, expires, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }

        private string GetCacheKey(string name)
        {
            return string.Format(null, "QuotaWarning_{0}_{1}", SPContext.Current.Site.ID, name);
        }
        
        protected override void OnLoad(EventArgs e)
        {
            double percentageUsed = 0d;
            bool showWarning = false;
            string color = string.Empty;
            string title = Resources.QuotaWarning_Title;
            string message = string.Empty;

            if(this.StorageMaximumLevel > 0)
            {
                percentageUsed = ((float)this.Storage / (float)this.StorageMaximumLevel * 100.0); 
            }

            if ((this.Storage > this.StorageWarningLevel) &&
                (this.StorageWarningLevel > 0))
            {
                showWarning = true;
                color = "yellow";
            }
            if (percentageUsed > 90d)
            {
                showWarning = true;
                color = "red";    
            }
            
            if (showWarning == true)
            {
                if (SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.ManageWeb) == true)
                {
                    message = string.Format(null,
                        Resources.QuotaWarning_Message_Owner,
                        percentageUsed.ToString("F1"),
                        SPContext.Current.Site.Url);
                }
                else
                {
                    message = string.Format(null,
                        Resources.QuotaWarning_Message_NotOwner,
                        percentageUsed.ToString("F1"));
                }

                string script =
                "ExecuteOrDelayUntilScriptLoaded(function() {" +
                "var statusId = SP.UI.Status.addStatus(\"" + title + "\",\"" + message + "\");" +
                "SP.UI.Status.setStatusPriColor(statusId,\"" + color + "\");" +
                "}, 'sp.ribbon.js');";

                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "QuotaWarning", script, true);           
            }
        }
    }
}
